package base

import (
	"errors"
	"cgs-server/server/model"
)

type Service interface {
	Save(mdl *model.DataUserModel) error
	Remove(mdl *model.DataUserModel) error
	RemoveLogic(mdl *model.DataUserModel) error
	Update(mdl *model.DataUserModel) error
	List(mdl *model.DataUserModel) (interface{}, error)
	GetOne(mdl *model.DataUserModel) (interface{}, error)
	Count(mdl *model.DataUserModel) int64

	Init(name ...string) error
}

type ServiceImpl struct {
	Repo Repository
}

// 创建数据库连接，如果传入集合名称则同时修改 collectionName
func (s *ServiceImpl) Init(name ...string) error {
	if len(name) == 0 {
		if s.Repo.GetCollectionName() == "" {
			return errors.New("current collection name is empty")
		}
		return s.Repo.InitDB()
	}
	return s.Repo.CreateDB(name[0])
}

func (s *ServiceImpl) Save(model *model.DataUserModel) error {
	return s.Repo.Insert(model)
	//return nil
}
func (s *ServiceImpl) Remove(model *model.DataUserModel) error {
	return s.Repo.Delete(model)
	//return nil
}
func (s *ServiceImpl) RemoveLogic(model *model.DataUserModel) error {
	//return s.Repo.Delete(model) == nil
	return nil
}
func (s *ServiceImpl) Update(model *model.DataUserModel) error {
	return s.Repo.Update(model)
	//return nil
}
func (s *ServiceImpl) List(model *model.DataUserModel) (interface{}, error) {
	return s.Repo.Find(model)
	//return nil, nil
}
func (s *ServiceImpl) GetOne(model *model.DataUserModel) (interface{}, error) {
	return s.Repo.FindOne(model)
	//return nil, nil
}
func (s *ServiceImpl) Count(mdl *model.DataUserModel) int64 {
	count, _ := s.Repo.Count(mdl)
	return count
}
